//
//  YHNetLogManager.m
//  SoYoungMobile40
//
//  Created by Jeakon on 17/2/17.
//  Copyright © 2017年 soyoung. All rights reserved.
//

#import "YHNetLogManager.h"
#import "JKDBHelper.h"


NSString *const xm_NOTIFICATION_NETLOG_CHANGED = @"xm_notification_netlog_changed";


@implementation YHNetLogModel

+ (NSArray *)findByCount:(NSUInteger)count {
    if (count <= 0) return nil;
    JKDBHelper *jkDB = [JKDBHelper shareInstance];
    NSMutableArray *users = [NSMutableArray array];
    [jkDB.dbQueue inDatabase:^(FMDatabase *db) {
        NSString *tableName = NSStringFromClass(self.class);
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY date DESC LIMIT %lu", tableName, count];
        FMResultSet *resultSet = [db executeQuery:sql];
        while ([resultSet next]) {
            JKDBModel *model = [[self.class alloc] init];
            for (int i = 0; i < model.columeNames.count; i++) {
                NSString *columeName = [model.columeNames objectAtIndex:i];
                NSString *columeType = [model.columeTypes objectAtIndex:i];
                if ([columeType isEqualToString:SQLTEXT]) {
                    //                    NSString *str = [[resultSet stringForColumn:columeName] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                    NSString *str = [[resultSet stringForColumn:columeName] stringByRemovingPercentEncoding];
                    [model setValue:str forKey:columeName];
                } else if ([columeType isEqualToString:SQLBLOB]) {
                    [model setValue:[resultSet dataForColumn:columeName] forKey:columeName];
                } else {
                    [model setValue:[NSNumber numberWithLongLong:[resultSet longLongIntForColumn:columeName]] forKey:columeName];
                }
            }
            [users addObject:model];
            FMDBRelease(model);
        }
    }];

    return users;
}

@end


@interface YHNetLogManager ()

@end


@implementation YHNetLogManager


+ (instancetype)sharedInstance {
    static dispatch_once_t once;
    static YHNetLogManager *manager;
    dispatch_once(&once, ^{
        manager = [[YHNetLogManager alloc] init];
    });
    return manager;
}


- (void)addLog:(YHNetLogModel *)log {
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [weakSelf realmDidAddedData];
        [log save];
    });
}

- (NSArray<YHNetLogModel *> *)logs {
    return [YHNetLogModel findByCount:100];
}

- (void)deleteAllLogs {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [YHNetLogModel clearTable];
    });
}

- (void)realmDidAddedData {
    [[NSNotificationCenter defaultCenter] postNotificationName:xm_NOTIFICATION_NETLOG_CHANGED object:nil];
}

@end
